package com.sailfish.template.infra.config;

import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.HikariPoolMXBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.management.JMX;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;

/**
 * @author XIAXINYU3
 * @date 2021/11/2
 */
@Slf4j
@Configuration
@ConditionalOnExpression("${spring.datasource.hikari.registerMbeans} == true")
public class DatabaseMonitorConfig {
    @Autowired
    HikariDataSource hikariDataSource;

    @Bean
    public HikariPoolMXBean poolProxy() throws MalformedObjectNameException {
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        ObjectName poolName = new ObjectName("com.zaxxer.hikari:type=Pool (" + hikariDataSource.getPoolName() + ")");
        return JMX.newMXBeanProxy(mBeanServer, poolName, HikariPoolMXBean.class);
    }
}
